package com.hongfasoft.servlet;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hongfasoft.util.DBManager;
import com.jspsmart.upload.SmartFiles;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

public class JspsmartUploadServlet extends HttpServlet
{

	private static final long serialVersionUID = 1330160775645241539L;

	private static final String allowFile = "jpg,png,gif,bmp,mp3,wma,wav,ogg,wmv,avi,mpg,rm,rmvb,mov,flv,3gp";

	public static final String imgRoot = "pubImgs/image";

	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		request.setCharacterEncoding("UTF-8");
		ServletContext src = request.getSession().getServletContext();

		SmartUpload smartUpload = new SmartUpload();
		// SmartUpload 的初始化
		smartUpload.setCharset("UTF-8");
		smartUpload.initialize(this.getServletConfig(), request, response);
		// 设定每个文件允许上传的最大长度
		smartUpload.setMaxFileSize(10 * 1024 * 1024);
		// 设定允许上传的文件的总长度，用于限制一次性上传的数据量大小
		smartUpload.setTotalMaxFileSize(3 * 10 * 1024 * 1024);
		// 用于限制上传那些带有指定扩展名的文件。若有文件扩展名被限制，则上传时组件将抛出异常。
		// smartUpload.setAllowedFilesList(allowFile + "," +
		// allowFile.toUpperCase());
		// 设定禁止上传的文件（通过扩展名限制）
		try
		{
			smartUpload.setDeniedFilesList("exe,bat,jsp");
		} catch (SQLException e1)
		{
			e1.printStackTrace();
			response.sendRedirect(src.getContextPath() + "/Error.html");
			return;
		}
		try
		{
			// 上传文件数据。对于上传操作，第一步执行initialize方法，第二步就要执行这个方法
			smartUpload.upload();
		} catch (SmartUploadException e2)
		{
			e2.printStackTrace();
			response.sendRedirect(src.getContextPath() + "/Error.html");
			return;
		}
		// 上传的总目录
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String todayFilePath = sdf.format(new Date(System.currentTimeMillis()));
		// String dirPath =
		// request.getSession().getServletContext().getRealPath("/NewsImgs/" +
		// todayFilePath);
		File f2 = new File(request.getSession().getServletContext().getRealPath(""));
		String dirPath = f2.getAbsolutePath();
		dirPath = dirPath + File.separatorChar + imgRoot + File.separatorChar + todayFilePath;
		// System.out.println(dirPath);
		File f = new File(dirPath);
		if (!f.exists())
		{
			f.mkdirs();
		}

		SmartFiles files = smartUpload.getFiles();
		String imgName = null;
		// System.out.println(request.getQueryString());
		for (int i = 0; files.getCount() > 0 && i < files.getCount(); i++)
		{
			com.jspsmart.upload.SmartFile file = files.getFile(i);
			// System.out.println("filedName=" + file.getFieldName() + " Name="
			// + file.getFileName() + " path=" + file.getFilePathName());
			System.out.println(file.getFileName());
			if (file.getFileName().lastIndexOf(".") < 0)
			{
				continue;
			}
			String extName = file.getFileName().substring(file.getFileName().lastIndexOf(".")).toLowerCase();
			imgName = sdf.format(new Date()) + "_" + new Random().nextInt(1000) + extName;
			try
			{
				file.saveAs(dirPath + "/" + imgName);
			} catch (Exception e)
			{
				System.out.println(dirPath + "/" + imgName);
				e.printStackTrace();
				// response.sendRedirect(src.getContextPath() + "/Error.html");
				// return;
			}
		}

		// 将所有文件保存到同一目录
		// saveAll(smartUpload, dirPath);
		// 将不同地区的文件存放到不同的目录中
		// saveSingle(smartUpload, dirPath);

		// 获取表单中的其它内容
		com.jspsmart.upload.SmartRequest rq = smartUpload.getRequest();
		// 获取指定参数之值。当参数不存在时，返回值为null
		// String parameterValue = rq.getParameter("subject");
		// System.out.println("value" + parameterValue);
		Map articleData = new HashMap();
		// 取得Request对象中所有参数的名字，用于遍历所有参数。它返回的是一个枚举型的对象
		Enumeration parameterName = rq.getParameterNames();
		while (parameterName.hasMoreElements())
		{
			String paramentername = (String) parameterName.nextElement();
			String paravalue = rq.getParameter(paramentername);
			articleData.put(paramentername, paravalue);
		}

		if (imgName != null && !"".equals(imgName))
		{
			articleData.put("imgurl", "../" + imgRoot + "/" + todayFilePath + "/" + imgName);
		}

		try
		{
			System.out.println(articleData);

			DBManager.saveArticles(articleData);
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendRedirect(src.getContextPath() + "/Error.html");
			return;
		}
		// 当一个参数可以有多个值时，用此方法来取其值。它返回的是一个字符串数组。当参数不存在时，返回值为null
		// rq.getParameterValues("subject");
		response.sendRedirect(src.getContextPath() + "/Success.html");
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		this.doPost(request, response);
	}

}
